package com.newsanalysis.analysis;

import org.springframework.stereotype.Component;

import java.util.*;
import java.util.regex.Pattern;

@Component
public class TextAnalyzer {
    private static final Set<String> STOP_WORDS = new HashSet<>(Arrays.asList(
            "的", "了", "和", "是", "在", "我", "有", "不", "人", "他", "这", "中", "也", "就", "为", "以",
            "to", "the", "and", "of", "in", "is", "that", "for", "on", "with", "as", "at", "be", "this", "by", "from"
    ));
    
    // 情感分析
    public String analyzeSentiment(String text) {
        // 简单的情感词典方法
        // 实际应用中可以使用更复杂的NLP库或机器学习模型
        
        // 正面词汇
        List<String> positiveWords = Arrays.asList(
                "好", "优秀", "棒", "成功", "进步", "提高", "喜欢", "赞", "欢迎", "支持",
                "good", "great", "excellent", "success", "progress", "improve", "like", "welcome", "support"
        );
        
        // 负面词汇
        List<String> negativeWords = Arrays.asList(
                "差", "糟糕", "失败", "问题", "困难", "下降", "反对", "批评", "不满", "担忧",
                "bad", "poor", "fail", "problem", "difficult", "decline", "against", "criticize", "worry"
        );
        
        // 计算情感得分
        int score = 0;
        for (String word : positiveWords) {
            if (text.contains(word)) {
                score++;
            }
        }
        
        for (String word : negativeWords) {
            if (text.contains(word)) {
                score--;
            }
        }
        
        // 确定情感倾向
        if (score > 0) {
            return "正面";
        } else if (score < 0) {
            return "负面";
        } else {
            return "中性";
        }
    }
    
    // 提取关键词
    public List<Map.Entry<String, Integer>> extractKeywords(String text, int limit) {
        // 分词处理
        // 在实际应用中，中文文本需要使用专业分词工具如jieba、HanLP等
        String[] words = text.split("\\s+");
        
        // 词频统计
        Map<String, Integer> wordFreq = new HashMap<>();
        for (String word : words) {
            // 简单的预处理
            word = word.toLowerCase().trim();
            word = word.replaceAll("[^\\p{L}\\p{N}]", ""); // 去除标点符号
            
            // 过滤停用词和过短的词
            if (word.length() < 2 || STOP_WORDS.contains(word)) {
                continue;
            }
            
            wordFreq.put(word, wordFreq.getOrDefault(word, 0) + 1);
        }
        
        // 排序
        List<Map.Entry<String, Integer>> sortedWords = new ArrayList<>(wordFreq.entrySet());
        sortedWords.sort((e1, e2) -> e2.getValue().compareTo(e1.getValue()));
        
        // 返回前N个关键词
        return sortedWords.subList(0, Math.min(limit, sortedWords.size()));
    }
    
    // 新闻分类
    public String classifyNews(String title, String content) {
        // 简单的规则分类方法
        // 实际应用中可以使用机器学习分类器
        
        String text = title + " " + content;
        text = text.toLowerCase();
        
        // 定义类别关键词
        Map<String, List<String>> categoryKeywords = new HashMap<>();
        categoryKeywords.put("政治", Arrays.asList("政府", "官员", "总统", "政策", "法律", "国家", "选举", "党", "政治"));
        categoryKeywords.put("经济", Arrays.asList("经济", "金融", "股市", "投资", "企业", "市场", "贸易", "财政", "银行"));
        categoryKeywords.put("科技", Arrays.asList("科技", "技术", "互联网", "软件", "硬件", "数字", "智能", "创新", "研发"));
        categoryKeywords.put("体育", Arrays.asList("体育", "运动", "比赛", "球队", "球员", "奥运", "冠军", "足球", "篮球"));
        categoryKeywords.put("娱乐", Arrays.asList("娱乐", "明星", "影视", "音乐", "电影", "电视", "综艺", "演员", "歌手"));
        categoryKeywords.put("教育", Arrays.asList("教育", "学校", "大学", "学生", "老师", "课程", "培训", "学习", "教学"));
        
        // 英文关键词
        categoryKeywords.get("政治").addAll(Arrays.asList("government", "official", "president", "policy", "law", "nation", "election", "party", "politics"));
        categoryKeywords.get("经济").addAll(Arrays.asList("economy", "finance", "stock", "investment", "business", "market", "trade", "fiscal", "bank"));
        categoryKeywords.get("科技").addAll(Arrays.asList("technology", "tech", "internet", "software", "hardware", "digital", "smart", "innovation", "development"));
        categoryKeywords.get("体育").addAll(Arrays.asList("sports", "game", "match", "team", "player", "olympic", "champion", "football", "basketball"));
        categoryKeywords.get("娱乐").addAll(Arrays.asList("entertainment", "celebrity", "movie", "music", "film", "tv", "show", "actor", "singer"));
        categoryKeywords.get("教育").addAll(Arrays.asList("education", "school", "university", "student", "teacher", "course", "training", "learning", "teaching"));
        
        // 计算各类别匹配度
        Map<String, Integer> categoryScore = new HashMap<>();
        for (Map.Entry<String, List<String>> entry : categoryKeywords.entrySet()) {
            int score = 0;
            for (String keyword : entry.getValue()) {
                if (text.contains(keyword)) {
                    score++;
                }
            }
            categoryScore.put(entry.getKey(), score);
        }
        
        // 找出得分最高的类别
        return categoryScore.entrySet().stream()
                .max(Map.Entry.comparingByValue())
                .map(Map.Entry::getKey)
                .orElse("其他");
    }
    
    // 计算热度指数
    public int calculateHotIndex(String title, String content, int viewCount) {
        // 基于标题长度、内容长度、浏览次数等因素计算热度
        int hotIndex = 0;
        
        // 标题因素
        if (title != null && !title.isEmpty()) {
            hotIndex += Math.min(title.length(), 30) / 2;
        }
        
        // 内容因素
        if (content != null && !content.isEmpty()) {
            hotIndex += Math.min(content.length(), 5000) / 500;
        }
        
        // 浏览因素（假设已有浏览数据）
        hotIndex += Math.min(viewCount, 1000) / 10;
        
        return hotIndex;
    }
}

